package main

import (
	"io/fs"
	"io/ioutil"
	"log"
	"os"
	"server/base"

	urfave "github.com/urfave/cli/v2"
)

func init() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	log.SetOutput(os.Stdout)
}

var runName = &urfave.Command{
	Name:  "name",
	Usage: "根据excel生成游戏名",
	Flags: []urfave.Flag{
		&urfave.StringFlag{
			Name:  "i",
			Usage: "excel文件路径",
			Value: "game.xlsx",
		},
		&urfave.StringFlag{
			Name:  "o",
			Usage: "输出文件",
			Value: "name.txt",
		},
	},
	Action: func(cctx *urfave.Context) error {
		in_file := cctx.String("i")
		log.Println("in_file:", in_file)
		out_file := cctx.String("o")
		log.Println("output_file:", out_file)
		exporter := &NameExporter{}
		out := exporter.ReadExcel(in_file)
		f, err := os.OpenFile(out_file, os.O_WRONLY|os.O_CREATE, 0777)
		if err != nil {
			log.Println("open out_file:", out_file, err)
		}
		defer f.Close()
		for _, name := range out {
			_, err := f.WriteString(name + "\n")
			base.Raise(err)
		}
		return nil
	},
}

var runGameTable = &urfave.Command{
	Name:  "js",
	Usage: "根据excel生成gametable.js",
	Flags: []urfave.Flag{
		&urfave.StringFlag{
			Name:  "i",
			Usage: "excel文件路径",
			Value: "game.xlsx",
		},
		&urfave.StringFlag{
			Name:  "o",
			Usage: "输出文件",
			Value: "gametable.js",
		},
	},
	Action: func(cctx *urfave.Context) error {
		in_file := cctx.String("i")
		log.Println("in_file:", in_file)
		out_file := cctx.String("o")
		log.Println("output_file:", out_file)
		exporter := &JsExporter{}
		out := exporter.ReadExcel(in_file)
		s := base.JsonString(out)
		s = "var gametable=" + s + ";"
		err := ioutil.WriteFile(out_file, []byte(s), fs.ModePerm)
		base.Raise(err)
		return nil
	},
}

var renameGames = &urfave.Command{
	Name:  "rename",
	Usage: "读取excel中的文件改名",
	Flags: []urfave.Flag{
		&urfave.StringFlag{
			Name:  "i",
			Usage: "excel文件路径",
			Value: "game.xlsx",
		},
	},
	Action: func(cctx *urfave.Context) error {
		in_file := cctx.String("i")
		log.Println("in_file:", in_file)
		renamer := &Renamer{}
		renamer.ReadExcel(in_file)
		return nil
	},
}

func main() {
	local := []*urfave.Command{
		runName,
		runGameTable,
		renameGames,
	}

	app := &urfave.App{
		Name:                 "gameshop exporter",
		Usage:                "",
		Version:              "0.1",
		EnableBashCompletion: true,
		Flags:                []urfave.Flag{},

		Commands: local,
	}
	app.Setup()

	if err := app.Run(os.Args); err != nil {
		log.Println("app.Run err:", err)
		return
	}
}
